rm(list = ls())
setwd('E:\\17_HuaDong\\teach\\MyLecture\\R\\code')
library(Synth)
# 载入数据
data(synth.data)

# create matrices from panel data that provide inputs for synth()
dataprep.out<-
  dataprep(
    foo = synth.data, # 数据框
    predictors = c("X1", "X2", "X3"), # 自变量
    predictors.op = "mean", # 多期自变量整合为一期自变量的运算方式，见讲义
    dependent = "Y", # 因变量
    unit.variable = "unit.num", # 个体id
    time.variable = "year", # 时间id
    special.predictors = list(  # 特殊自变量，可能整合方式不同，需要特殊处理
      list("Y", 1991, "mean"),
      list("Y", 1985, "mean"),
      list("Y", 1980, "mean")
    ),
    treatment.identifier = 7, # 处理组id
    controls.identifier = c(29, 2, 13, 17, 32, 38), # 控制组id
    time.predictors.prior = c(1984:1989), # 处理前时期
    time.optimize.ssr = c(1984:1990), # 最小化差异的时期
    unit.names.variable = "name",
    time.plot = 1984:1996
  )

# 可以观察一下X0
dataprep.out$X0
# 合成控制估计
synth.out <- synth(dataprep.out)
# 各个控制个体的权重
round(synth.out$solution.w,2)
# 干预前干预组和合成控制组结果变量的差距
gaps<- dataprep.out$Y1plot-(dataprep.out$Y0plot %*% synth.out$solution.w) 
gaps
# 绘制干预组和合成控制组结果变量轨迹
path.plot(dataprep.res = dataprep.out,synth.res = synth.out) # 输入预处理数据以及回归数据即可
# 绘制干预组和合成控制组结果变量距离的轨迹
gaps.plot(dataprep.res = dataprep.out,synth.res = synth.out)
